package cn.xorange.commons.system.controller.system;

import cn.xorange.commons.core.basic.bean.ResultBean;
import cn.xorange.commons.core.basic.controller.BaseController;
import cn.xorange.commons.security.entity.SecurityUser;
import cn.xorange.commons.security.utils.SecurityUtils;
import cn.xorange.commons.system.entity.system.SysUser;
import cn.xorange.commons.system.service.System.ISysOrgService;
import cn.xorange.commons.system.service.System.ISysPostService;
import cn.xorange.commons.system.service.System.ISysRoleService;
import cn.xorange.commons.system.service.System.ISysUserService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.Set;

/**
 * @author : yangjian
 * date : 2025/2/24
 * description :
 */
@RestController
@RequestMapping("/system/user/profile")
public class SysUserProfileController extends BaseController {

    @Resource
    ISysUserService service;
    @Resource
    ISysPostService postService;
    @Resource
    ISysRoleService roleService;

    @GetMapping()
    public ResultBean getUserProfile(){
        SecurityUser securityUser = SecurityUtils.getUser();

        SysUser user = service.getById(securityUser.getUserId());

        Set<String> keys = securityUser.getRoleKeys();
        String roleNames = "";
        if(Objects.nonNull(keys) && !keys.isEmpty()){
            roleNames = roleService.getRoleNames(keys);
        }
        String postNames = postService.getPostNamesByUserId(securityUser.getUserId());
        return ResultBean.onSuccess(user).put("roleGroup", roleNames).put("postGroup", postNames);
    }

    @PutMapping
    public ResultBean setUserProfile(@RequestBody SysUser user){
        Long userId = SecurityUtils.getUserId();
        user.setUserId(userId);
        service.update(user);
        return ResultBean.onSuccess();
    }

    @PutMapping("/editPwd")
    @Transactional
    public ResultBean editUserPwd(@RequestBody SysUser sysUser){
        Long userId = SecurityUtils.getUserId();
        String newPwd = sysUser.getParams().getString("password");
        if(Objects.isNull(sysUser.getPassword()) || Objects.isNull(newPwd)){
            return ResultBean.onFail("新旧密码不能为空");
        }

        SysUser oUser = service.getById(userId);
        boolean match =  SecurityUtils.matchesPassword(sysUser.getPassword(),oUser.getPassword());
        if(!match){
            return ResultBean.onFail("原密码不正确");
        }
        String newPwdEncode = SecurityUtils.encryptPassword(newPwd);
        SysUser user = new SysUser();
        user.setUserId(userId);
        user.setPassword(newPwdEncode);
        service.update(user);
        return ResultBean.onSuccess();
    }

}
